package com.ydlclass.handler;

import com.ydlclass.bootstrap.ClientBootstrap;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author it楠老师
 * @createTime 2023-03-23
 */
@Slf4j
public class ChannelProvider {

    private static final ChannelProvider channelProvider = new ChannelProvider();

    private ChannelProvider(){}

    public static ChannelProvider getInstance() {
        return channelProvider;
    }

    // channel通道的缓存
    // key:是服务名-- hostAddress + ":" + port;
    private final Map<String,Channel> channelCache = new ConcurrentHashMap<>(16);

    public Channel selectChannel(InetSocketAddress inetSocketAddress){
        // 1、封装channel的key
        String channelKey = createChannelKey(inetSocketAddress);

        //2、从缓存获取channel
        Channel channel = channelCache.get(channelKey);

        //3、未命中，则执行连接操作，并将channel缓存
        if(channel == null){
            channel = ClientBootstrap.getInstance().connect(inetSocketAddress);
            channelCache.put(channelKey,channel);
            if(log.isDebugEnabled()){
                log.debug("--> A channel instance[{}] is cached.",channelKey);
            }
        }
        return channel;
    }

    public void OfflineChannel(InetSocketAddress inetSocketAddress){
        String channelKey = createChannelKey(inetSocketAddress);
        Channel channel = channelCache.remove(channelKey);
        if(channel == null){
            log.warn("--> You are trying to delete a channel[{}] that does not exist.",channelKey);
        }
    }

    private String createChannelKey(InetSocketAddress inetSocketAddress){
        if (inetSocketAddress == null){
            throw new IllegalArgumentException("Your view creates a key for a channel that does not exist.");
        }

        String hostAddress = inetSocketAddress.getAddress().getHostAddress();
        int port = inetSocketAddress.getPort();
        return hostAddress + ":" + port;
    }

}
